/*
 * Copyright (C) 2012 Damien Girard <dgirard@nativesoft.fr>
 * Copyright (C) 2012 Sebastien Baudrand <sebbaudrand@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package fr.umlv.qroxy.http;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *  Get an exception if the header is not correct
 * 
 * @author Damien Girard <dgirard@nativesoft.fr>
 * @author Sebastien BAUDRAND <sebbaudrand@gmail.com>
 */
public class HttpException extends Exception {

    private final HttpCodes httpCode;

    /**
     * Creates a new HTTP Exception.
     * 
     * @param httpCommand The http command.
     * @param message The message associated to this exception.
     */
    public HttpException(HttpCodes httpCode, String message) {
        super(message);

        this.httpCode = httpCode;
    }
    
     public ByteBuffer getPage() {
        StringBuilder sb = new StringBuilder();
        sb.append("HTTP/1.1 ").append(httpCode.getCode()).append(" ").append(httpCode.getDescription());
        sb.append("\r\n");
        sb.append("\r\n");
        sb.append("<html><h1>").append(httpCode.getCode()).append(" ").append(httpCode.getDescription()).append("</h1>");
        sb.append("<p>").append(this.getMessage()).append("</p>").append("</html>");
        try {
            return ByteBuffer.wrap(sb.toString().getBytes("ASCII")); // Should not fire any exception.
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(HttpCodes.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    /**
     * The HTTP error code.
     */
    public HttpCodes getHttpCode() {
        return httpCode;
    }

    @Override
    public String toString() {
        return httpCode.getCode() +" "+ httpCode.getDescription() +" "+ this.getLocalizedMessage();
    }
    
    
}
